<?php
header("Content-type: text/plain; charset=utf-8", true);

if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET["service-source"])) {
    echo file_get_contents(__FILE__);
    return;
}

session_start();

if (!isset($_SESSION["Multiservice.CreatureNo"]))
    $_SESSION["Multiservice.CreatureNo"] = 0;

require_once("lib/jsonss.php");

class VerbService extends JSONSSService {
    public function Create($p) {
        if (isset($_SESSION["Multiservice.Creature"]))
            throw new JSONSSError(502, "Already created, behold!");
        else
            $_SESSION["Multiservice.Creature"] = "Creature No. " . ++$_SESSION["Multiservice.CreatureNo"];
    }

    public function __construct() {
        $this->add_method("Create", "create");
    }
}

class NounService extends JSONSSService {
    public function getCreature() { // implemented as read-only, read-once property
        if (!isset($_SESSION["Multiservice.Creature"]))
            return null;
        else {
            $res = $_SESSION["Multiservice.Creature"];
            unset($_SESSION["Multiservice.Creature"]);
            return $res;
        }
    }

    public function __construct() {
        $this->add_property("Creature", "creature", "getCreature", "");
    }
}

class QuestionService extends JSONSSService {
    public function __construct() {
        $this->add_event("Created");
    }
    public function ping() {
        if (isset($_SESSION["Multiservice.Creature"]))
            $this->fire_event("Created", $_SESSION["Multiservice.Creature"]);
    }
}

$server = new JSONSSServer();
$server->add_service(new VerbService(), "VerbService", "verb-service");
$server->add_service(new NounService(), "NounService", "noun-service");
$server->add_service(new QuestionService(), "QuestionService", "question-service");
$server->process_request();

session_commit();
